import { Layout, Menu, type MenuProps } from 'antd';
import { Content, Footer } from 'antd/es/layout/layout';
import { useEffect, useMemo, useState } from 'react';
import { useMatches, useNavigate } from 'react-router-dom';

import Scrollbar from '@/components/scrollbar';
import { usePathname, useRouteToMenuFn, useRouteToMenuBadgeFn } from '@/router/hooks';
import { useKnowFlattenedRoutes } from '@/router/hooks/use-flattened-routes';
import { useKnowPermissionRoutes } from '@/router/hooks/use-permission-routes';
import { menuFilter } from '@/router/utils';
import { useSettingActions, useSettings } from '@/store/settingStore';
import { ThemeLayout, ThemeMode } from '@/types/enum';

import { NAV_WIDTH, BASE } from '../config';

import NavLogo from './nav-logo';
import Account from '@/layouts/_common/account';
import { useInitializeData } from '@/store/configStore';

const { Sider } = Layout;

type Props = {
  closeSideBarDrawer?: () => void;
};
export default function NavVertical(props: Props) {
  const navigate = useNavigate();
  const matches = useMatches();
  const pathname = usePathname();
  const [value, setValue] = useState({ path: 'datasets/approval', badge: 0 });

  const settings = useSettings();
  const { themeLayout, themeMode, darkSidebar } = settings;
  const { setSettings } = useSettingActions();

  // const routeToMenuFn = useRouteToMenuFn();
  const routeToMenuBadgeFn = useRouteToMenuBadgeFn();
  const permissionRoutes = useKnowPermissionRoutes();
  const flattenedRoutes = useKnowFlattenedRoutes();
  const initializeData = useInitializeData();

  const collapsed = useMemo(() => themeLayout === ThemeLayout.Mini, [themeLayout]);

  const menuList = useMemo(() => {
    if (!initializeData?.license_edition) {
      return []
    }
    const menuRoutes = menuFilter(permissionRoutes);
    return routeToMenuBadgeFn(menuRoutes, [value]);
  }, [routeToMenuBadgeFn, permissionRoutes, value]);

  const selectedKeys = useMemo(() => [pathname], [pathname]);

  const [openKeys, setOpenKeys] = useState<string[]>([]);
  // 首次加载时设置 openKeys
  useEffect(() => {
    if (!collapsed) {
      const keys = matches
        .filter((match) => match.pathname !== '/' && match.pathname !== pathname)
        .map((match) => match.pathname);
      setOpenKeys(keys);
    }
  }, [collapsed, matches, pathname]);

  const handleToggleCollapsed = () => {
    setSettings({
      ...settings,
      themeLayout: collapsed ? ThemeLayout.Vertical : ThemeLayout.Mini,
    });
  };

  const onClick: MenuProps['onClick'] = ({ key }) => {
    const nextLink = flattenedRoutes?.find((e) => e.key === key);
    const url = BASE + key;

    if (nextLink?.hideTab && nextLink?.frameSrc) {
      window.open(nextLink?.frameSrc, '_blank');
      return;
    }

    navigate(url);
    props?.closeSideBarDrawer?.();
  };

  const handleOpenChange: MenuProps['onOpenChange'] = (keys) => {
    // 关闭时也触发一次，刚好设置为 []
    setOpenKeys(keys);
  };

  const sidebarTheme = useMemo(() => {
    if (themeMode === ThemeMode.Dark) {
      return darkSidebar ? 'light' : 'dark';
    }
    return darkSidebar ? 'dark' : 'light';
  }, [themeMode, darkSidebar]);

  // console.log(selectedKeys);

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={collapsed}
      width={NAV_WIDTH}
      theme={sidebarTheme}
      className="!fixed left-0 top-0 h-screen"
      style={{ background: '#fff' }}
    >
      <Layout className="flex h-full flex-col" style={{ background: '#fff' }}>
        <NavLogo collapsed={collapsed} onToggle={handleToggleCollapsed} />
        <Layout className="flex-1 bg-white">
          {/* 添加 flex-1 使内容区域占据剩余空间 */}
          <Content className="bg-white">
            <Scrollbar className="h-full">
              <Menu
                mode="inline"
                items={menuList}
                theme={sidebarTheme}
                selectedKeys={selectedKeys.map((item) => item.replace(BASE, ''))}
                openKeys={openKeys}
                onOpenChange={handleOpenChange}
                className="!border-none"
                onClick={onClick}
              />
            </Scrollbar>
          </Content>
        </Layout>
        <Footer style={{ padding: '0px', background: '#fff' }}>
          <Account />
        </Footer>
      </Layout>
    </Sider>
  );
}
